﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using BBB.Valuta.Common;
using BBB.Valuta.Converters;
using BBB.Valuta.Entity;
using BBB.Valuta.Savers;


namespace BBB.Valuta
{
    public partial class MainForm : Form
    {
        private bool _save = true;

        public MainForm()
        {
            InitializeComponent();
            editToolStripButton.Enabled = false;
            Text = " Валюта v-" + Assembly.GetExecutingAssembly().GetName().Version.ToString();
            loadData();
            SetSaveParam(true);
        }

        private void loadData()
        {
            if (receiptsBindingSource.DataSource == null)
            {
                receiptsBindingSource.DataSource = new ReceiptsBindingList<Receipt>(new List<Receipt>());
            }
            if (Settings.GetInstance().Departments.Count > 0)
            {
                departmentToolStripComboBox.Items.Clear();
                departmentToolStripComboBox.Items.AddRange(
                    Settings.GetInstance().Departments.Select(d => d.Display).ToArray());
                if (departmentToolStripComboBox.Text == string.Empty)
                {
                    departmentToolStripComboBox.SelectedIndex = 0;
                }
            }
        }

        private void SetSaveParam (bool isSave)
        {
            _save = isSave;
            saveToolStripButton.Enabled = !_save;
        }

        private void SaveReceipts()
        {
            WorkReceipts.SaveReceiptsInXML(((ReceiptsBindingList<Receipt>)receiptsBindingSource.DataSource).ToList(),
                                           Environment.CurrentDirectory +
                                           String.Format("\\Arc\\{0}.xml",
                                                         DateTime.Now.ToString("dd-MM-yy-hh-mm-ss")));
        }

        private void LoadButton_Click(object sender, EventArgs e)
        {
            try
            {
                DownloadType dt;
                if (new SelectTypeDownload().ShowDialog(out dt) == DialogResult.OK)
                {
                    ReceiptsBindingList<Receipt> rec = (ReceiptsBindingList<Receipt>)receiptsBindingSource.DataSource;
                    switch (dt)
                    {
                        case DownloadType.DBF:
                            {
                                using (FolderBrowserDialog dlg = new FolderBrowserDialog())
                                {
                                    dlg.Description = "Вкажіть шлях";
                                    if (dlg.ShowDialog() == DialogResult.OK)
                                    {
                                        rec.AddRange(WorkReceipts.LoadReceiptsFromDB(dlg.SelectedPath));

                                    }
                                }

                                break;
                            }
                        case DownloadType.XML:
                            {
                                if (openFileDialog.ShowDialog() == DialogResult.OK)
                                {
                                    rec.AddRange(WorkReceipts.LoadReceiptsFromXML(openFileDialog.FileName));
                                }
                                break;
                            }
                    }
                    receiptsBindingSource.DataSource = rec;
                    SetSaveParam(false);
                }
            }
            catch(Exception)
            {
                MessageBox.Show("Неможливо завантажити дані");
            }
        }

        private void receiptsDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridViewColumn col = receiptsDataGridView.Columns[e.ColumnIndex];
            if (col.DataPropertyName == "IsSale")
            {
                e.Value = e.Value.ToString() != "False" ? "П" : "К";
            }
        }

        private void currencyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new CatalogForm(CatalogType.Valuta).ShowDialog();
            loadData();
        }

        private void departmentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new CatalogForm(CatalogType.Department).ShowDialog();
            loadData();
        }

        private void addReceipt (Receipt rec)
        {
            receiptsBindingSource.Add(rec);
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Settings.SaveSettings();
        }

        private void printersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                new CatalogForm(CatalogType.Printer).ShowDialog();
                loadData();

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }


        }

        private void editToolStripButton_Click(object sender, EventArgs e)
        {
            AddReceiptForm adRecForm = new AddReceiptForm((Receipt)receiptsBindingSource.Current);
            if (adRecForm.ShowDialog() == DialogResult.OK)
            {
                receiptsDataGridView.Refresh();
                SetSaveParam(false);
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_save && receiptsBindingSource.Count < 1)
                return;
            DialogResult = MessageBox.Show("Зберігати будемо ?", "", MessageBoxButtons.YesNoCancel,
                                           MessageBoxIcon.Question, MessageBoxDefaultButton.Button3);
            switch (DialogResult)
            {
                case DialogResult.Yes:
                    {
                        try
                        {
                            SaveReceipts();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        break;
                    }
                case DialogResult.No:
                    {
                        break;
                    }
                case DialogResult.Cancel:
                    {
                        e.Cancel = true;
                        break;
                    }
            }
        }

        private void receiptsBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            if (receiptsBindingSource.Current != null)
            {
                editToolStripButton.Enabled = true;
                deleteToolStripButton.Enabled = true;
            }
            else
            {
                editToolStripButton.Enabled = false;
                deleteToolStripButton.Enabled = false;
            }
        }

        private void clearToolStripButton_Click(object sender, EventArgs e)
        {

            receiptsDataGridView.DataSource = new List<Receipt>();
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                SaveReceipts();
                SetSaveParam(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void receiptsBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            SetSaveParam(false);
        }

        private void ExportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string destination;
            bool isPrinter;
            Saver saver = null;
            Converter converter = null;
            if (new PrinterSelect().ShowDialog(out isPrinter, out destination) != DialogResult.OK)
                return;

            if (isPrinter)
            {
                saver = new PrintSaver(destination);
            }
            else
            {
                saver = new FileSaver(destination);
            }

            switch (((ToolStripMenuItem) sender).Name)
            {
                case "receiptsExportToolStripMenuItem":
                    {
                        converter = new ReceiptsConverter();
                        break;
                    }
                case "salesregisterToolStripMenuItem":
                    {
                        DateTime time = DateTime.Now;
                        if (new InputTime().ShowDialog(out time) == DialogResult.OK)
                        {
                            converter = new RegisterConverter {IsSalesRegistry = true, TimeConvert = time};
                        }
                        else
                        {
                            return;
                        }
                        break;
                    }
                case "payRegisterToolStripMenuItem":
                    {
                        DateTime time = DateTime.Now;
                        if (new InputTime().ShowDialog(out time) == DialogResult.OK)
                        {
                            converter = new RegisterConverter {IsSalesRegistry = false, TimeConvert = time};
                        }
                        else
                        {
                            return;
                        }
                        break;
                    }
            }
            if (converter == null || saver == null)
                throw new Exception("Помилка");
            converter.Department =
                Settings.GetInstance().Departments.First(d => d.Display == departmentToolStripComboBox.Text);
            converter.Receipts = ((ReceiptsBindingList<Receipt>) receiptsBindingSource.DataSource).ToList();
            converter.Build();
            saver.Body = (string) converter.GetResult();
            saver.Execute();

        }

        private void operationToolStripSplitButton_ButtonClick(object sender, EventArgs e)
        {
            if (operationToolStripSplitButton.IsOnDropDown)
                operationToolStripSplitButton.HideDropDown();
            else
                operationToolStripSplitButton.ShowDropDown();
        }

        private void deleteToolStripButton_Click(object sender, EventArgs e)
        {
            receiptsBindingSource.RemoveCurrent();
            SetSaveParam(false);
        }

        private void addToolStripButton_Click(object sender, EventArgs e)
        {
            AddReceiptForm adRecForm = new AddReceiptForm();
            adRecForm.AddReceipt += addReceipt;
            adRecForm.ShowDialog();
        }
    }
}
